package com.lj.service;

import com.lj.dao.LoginLogDao;
import com.lj.dao.RegisterLogDao;
import com.lj.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RegisterLogDao registerDao;
    @Autowired
    private LoginLogDao loginDao;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final int FAIL_TIMES = 3;

    private static final String FAIL_KEY = "FAIL:KEY";

    private static final int TIME_INTERVAL = 10;

    private RedisAtomicInteger getRedisCounter(String key) {
        RedisAtomicInteger counter = new RedisAtomicInteger(key, stringRedisTemplate.getConnectionFactory());

        if(counter.get() == 0) {
            counter.expire(TIME_INTERVAL, TimeUnit.MINUTES);
        }
        return counter;
    }

    public String loginService(String username, String password){
        String key = FAIL_KEY + username;
        RedisAtomicInteger counter = getRedisCounter(key);

        if(counter.get() >= FAIL_TIMES) {
            stringRedisTemplate.expire(key, 1, TimeUnit.MINUTES);
            return "登陆失败达到上限";
        }
        boolean validSuccess = userDao.getUserByUserNameAndPassword(username,password);
        if(validSuccess == false){
            counter.getAndIncrement();
            userDao.increaseLoginFailedTimes(username);
            return "登陆失败次数" + counter;
        }
        userDao.increaseLoginTimes(username);
        return "登陆成功";
    }

    public boolean registerService(String username, String password){

        //用户名不存在，创建user，创建注册日志
        userDao.registerDao(username,password);
        registerDao.creatRegisterLog(username);
        return true;
    }


}
